using System;
using System.Web;
using System.Web.Mail;
using System.Xml;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Net;


namespace newtelligence.DasBlog.Web.Services
{
	/// <summary>
	/// Summary description for ClickThroughHandler.
	/// </summary>
    public partial class WebWebServices
	{
		[OperationContract, WebGet(UriTemplate="/ct?id={sourceId}&url={targetUrl}")]
        public void ClickThroughHandler( string sourceId, string targetUrl )
        {
            if ( !siteConfig.EnableClickThrough )
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.ServiceUnavailable;
                return;
            }                                      

            if ( targetUrl == null || targetUrl.Length == 0 ) 
            {
                WebOperationContext.Current.OutgoingResponse.Location = Utils.GetStartPageUrl(siteConfig);
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Redirect;
                WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
                return;
            }
            else
            {
                try
                {
                    Entry entry = dataService.GetEntry( sourceId );
                    if ( entry != null )
                    {
                        // we'll check whether the entry exists just to avoid trash in the DB
                        loggingService.AddClickThrough(
                            new LogDataItem(targetUrl,Utils.GetPermaLinkUrl(siteConfig, sourceId ),WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.UserAgent], HttpContext.Current.Request.UserHostName));
                    }
                }
                catch( Exception exc )
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,exc);
                }
            }
            WebOperationContext.Current.OutgoingResponse.Location = targetUrl;
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Redirect;
        }
	}
}
